<template>
<div class="abc" ref="abc">
  <ul>
    <li
      v-for="item of letters"
      :key="item"
      :ref="item"
      @click="handleClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >{{item}}</li>
  </ul>
</div>
</template>

<script>
export default {
  data () {
    return {
      touchStatus: false,
      letter: '',
      abcTop: 0,
      letterTop: 0,
      letterHeight: 0
    }
  },
  props: {
    cities: Object
  },
  computed: {
    letters () {
      let arr = []
      for (let i in this.cities) {
        arr.push(i)
      }
      return arr
    }
  },
  updated () {
    this.abcTop = this.$refs['abc'].offsetTop
    this.letterTop = this.$refs['A'][0].offsetTop
    this.letterHeight = this.$refs['A'][0].offsetHeight
  },
  methods: {
    handleClick (e) {
      this.letter = e.target.innerText
      this.$emit('change', this.letter)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      let timer = null
      // 使用定时器截流函数，提高性能
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        let touchY = e.touches[0].clientY
        let disY = touchY - this.abcTop - this.letterTop
        let index = Math.floor(disY / this.letterHeight)
        if (index >= 0 && index < this.letters.length) {
          this.letter = this.letters[index]
          this.$emit('change', this.letter)
        }
      }, 16)
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style>
.abc{
  width:.4rem;
  text-align:center;
  line-height:.45rem;
  position:absolute;
  right:0;
  top:1.8rem;
  bottom:0;
  color:#00bcd4;
  /*垂直方向居中*/
  display:flex;
  flex-direction:column;
  justify-content:center;
  overflow:hidden;
}
</style>
